﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PageNumberingControl : System.Web.UI.UserControl
{
    public int CurrentPage   { get; set; }
    public int NumberOfPages { get; set; }

    private const int MaxButtons = 7;
    private int numberOfButtons;
    private LinkButton[] pageButtons;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (CurrentPage == 0 && HiddenPageNumber.Value != "")
            CurrentPage = int.Parse(HiddenPageNumber.Value);
        numberOfButtons = Clamp(MaxButtons, 0, NumberOfPages);
        pageButtons = new LinkButton[numberOfButtons];

        int m = MaxButtons / 2 + 1;

        for (int i = 0; i < pageButtons.Length; i++)
        {
            int offset = Clamp(CurrentPage - m, 0, NumberOfPages - MaxButtons);
            pageButtons[i] = new LinkButton();

            pageButtons[i].Text = (i+1 + offset).ToString();
            pageButtons[i].Click += new EventHandler(PageNumberingControl_Click);

            paginationPanel.Controls.Add(pageButtons[i]);
        }
    }

    private void PageNumberingControl_Click(object sender, EventArgs e)
    {
        LinkButton button = (LinkButton)sender;
        int pageNumber =  int.Parse(button.Text); // should catch exception

        HiddenPageNumber.Value = button.Text;
    }

    private int Clamp(int value, int min, int max)
    {
        return (value < min) ? min : (value > max) ? max : value;
    }
}